package com.nanosn.coffeemaker;

import com.nanosn.coffeemaker.application.commands.Compile;
import com.nanosn.coffeemaker.application.commands.Generate;
import com.nanosn.coffeemaker.application.commands.RunDerby;
import com.nanosn.coffeemaker.application.commands.RunServerTomcat;
import com.nanosn.coffeemaker.application.commands.RunServer;
import com.nanosn.coffeemaker.application.commands.Shell;
import com.nanosn.coffeemaker.application.commands.Sql;
import com.nanosn.coffeemaker.application.commands.StartApplication;
import com.nanosn.coffeemaker.application.commands.StartProject;
import com.nanosn.coffeemaker.application.commands.SyncDB;
import com.nanosn.coffeemaker.java.SystemClassLoaderModifier;
import com.nanosn.util.parsers.commandline.CommandsRegistry;
import java.io.File;
import java.util.Enumeration;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;

/**
 * The main entry point of the application.
 * @author selkhateeb
 */
public class Main {

    /**
     * Main function in the application
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        PrepareLogger(Level.FINEST);
        Project.logger.fine("Application Started...");

        try {
            //TODO: not all commands require this also its wrong for some commands (startproject..)
//            SystemClassLoaderModifier.addFile(new File("../"));
            SystemClassLoaderModifier.addFile(new File(Project.getDevelopmentDirectory()));

            //ParseArguments(args);
            CommandsRegistry cr = new CommandsRegistry(
                    StartProject.class,
                    StartApplication.class,
                    Shell.class,
                    Sql.class,
                    SyncDB.class,
                    RunServer.class,
                    RunServerTomcat.class, //FOR DEBUGGING ONLY
                    Compile.class, // FOR DEBUGGING ONLY
                    MainForTryingThingsOut.class, // FOR DEBUGGING ONLY
                    RunDerby.class, // FOR DEBUGGING ONLY
                    Generate.class);

            //Clean the temp directory
            CleanTemp(new File(Project.TMP));
//            CleanTemp(new File(Project.TMP));


            cr.run(args);

        }
        catch (Exception ex) {
            Project.logger.log(Level.SEVERE, ex.getMessage(), ex);
        }

        Project.logger.fine("Application Ended...");

    }

    public static void CleanTemp(File tempDir) {
        if (!tempDir.exists()) {
            return;
        }
        for (File file : tempDir.listFiles()) {
            if (file.isDirectory()) {
                if (file.listFiles().length == 0) {
                    file.delete();
                }
                else {
                    CleanTemp(file);
                    file.delete();
                }
            }
            else {
                file.delete();
            }
        }
    }

//    /**
//     * Parses the command line arguments and run application options
//     * Pre: User passed command line argument
//     * Post: Project started with specified options
//     * @param args
//     * @throws java.lang.Exception
//     */
//    private static void ParseArguments(final String[] args) throws Exception {
//        final ICommandLineArguments cla =
//                CliFactory.parseArguments(ICommandLineArguments.class, args);
//
//
//        //Set the logger if user passed debug or verbose
//        if (cla.isDebug()) {
//            PrepareLogger(Level.ALL);
//        }
//        else if (cla.isVerbose()) {
//            PrepareLogger(Level.FINE);
//        }
//        else {
//            PrepareLogger(Level.INFO);
//        }
//
//
//        //Run the applicaiton based on the user selection
//        if (cla.isStartProject()) {
//            // <editor-fold defaultstate="collapsed" desc="Logging">
//            if (Project.logger.isLoggable(Level.FINE)) {
//                Project.logger.fine("User is creating new project named: " + cla.getStartProject());
//            }
//            // </editor-fold>
//            //User is creating new project
//            Project.StartProject(cla.getStartProject());
//        }
//        else if (cla.isStartApplication()) {
//            Project.StartApplicaiton(cla.getStartApplication());
//        }
//        else if (cla.isVersion()) {
//            System.out.println(Project.getVersion());
//        }
//        else if (cla.isSql()) {
//            Project.PrintSqlSchema(cla.getSql());
//        }
//        else if (cla.isRunServer()) {
//            Project.RunServerTomcat();
//        }
//        else if (cla.isShell()) {
//            Project.startShell();
//        }
//        else {
//            final Cli<ICommandLineArguments> cli = CliFactory.createCli(ICommandLineArguments.class);
//            System.out.println(cli.getHelpMessage());
//        }
//    }
    /**
     * Prepares the logger to log all messages to console.
     * Pre:
     * Post: The logger set to log to console
     * @throws java.lang.SecurityException
     */
    private static void PrepareLogger(final Level logLevel) throws
            SecurityException {

        final ConsoleHandler handler = new ConsoleHandler();
        handler.setLevel(logLevel);
        handler.setFormatter(new LogFormatter());
        Project.logger.setUseParentHandlers(false);
        Project.logger.addHandler(handler);
        final LogManager lm = LogManager.getLogManager();
        final Enumeration<String> e = lm.getLoggerNames();
        while (e.hasMoreElements()) {
            String w = e.nextElement();
            Logger l = lm.getLogger(w);
            l.setLevel(logLevel);
        }
    }
}
